package com.hzy.utils.pay;

import com.hzy.constant.ConfigConstants;
import com.hzy.utils.MD5;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 微信支付用这个解析xml
 *
 * @author Administrator
 */
public class CommonPayUtil {

    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
     *
     * @param strXml string类型的xml
     *
     * @return 解析xml, 返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
     */
    public static SortedMap<String, String> parseMap(String strXml) throws JDOMException, IOException {
        if (null == strXml || "".equals(strXml)) {
            return null;
        }
        strXml = strXml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
        SortedMap<String, String> m = new TreeMap<>();
        InputStream in = new ByteArrayInputStream(strXml.getBytes(StandardCharsets.UTF_8.name()));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        for (Object o : list) {
            Element e = (Element) o;
            String k = e.getName();
            String v;
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = CommonPayUtil.getChildrenText(children);
            }

            m.put(k, v);
        }
        // 关闭流  
        in.close();
        return m;
    }

    /**
     * 获取子结点的xml
     *
     * @param children 子节点
     *
     * @return String
     */

    private static String getChildrenText(List children) {
        StringBuilder sb = new StringBuilder();
        if (!children.isEmpty()) {
            for (Object child : children) {
                Element e = (Element) child;
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<").append(name).append(">");
                if (!list.isEmpty()) {
                    sb.append(CommonPayUtil.getChildrenText(list));
                }
                sb.append(value);
                sb.append("</").append(name).append(">");
            }
        }
        return sb.toString();
    }

    /**
     * 输出XML
     *
     * @param parameters map
     *
     * @return xml
     */
    static String parseXML(SortedMap parameters) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        for (Object e : es) {
            Map.Entry entry = (Map.Entry) e;
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"appkey".equals(k)) {
                sb.append("<").append(k).append(">").append(v).append("</").append(k).append(">\n");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    /**
     * 把map里的内容转成xml字符串
     *
     * @param param xml的map
     *
     * @return xml字符串
     */
    public static String getMapToXML(Map<String, String> param) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sb.append("<").append(entry.getKey()).append(">");
            sb.append(entry.getValue());
            sb.append("</").append(entry.getKey()).append(">");
        }
        sb.append("</xml>");
        return sb.toString();
    }

    /**
     * 要求外部（商户）订单号必须唯一。
     * 通过用户id生成
     *
     * @return 商户订单号，20位
     */
    public static String getOutTradeNo(int userId) {
        String key = String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()) + userId;
        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 20);
        return key;
    }


    /**
     * 验证回调签名
     *
     * @return 签名正确与否
     */
    public static boolean isWxSign(Map<String, String> map) {
        String signFromAPIResponse = map.get("sign");
        if (signFromAPIResponse == null || "".equals(signFromAPIResponse)) {
            System.out.println("API返回的数据签名数据不存在，有可能被第三方篡改!!!");
            return false;
        }
        //过滤空 设置 TreeMap
        SortedMap<String, String> packageParams = new TreeMap<>();
        for (String parameter : map.keySet()) {
            String parameterValue = map.get(parameter);
            String v = "";
            if (null != parameterValue) {
                v = parameterValue.trim();
            }
            packageParams.put(parameter, v);
        }

        StringBuilder sb = new StringBuilder();
        Set es = packageParams.entrySet();

        for (Object e1 : es) {
            Map.Entry entry = (Map.Entry) e1;
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (!"sign".equals(k) && null != v && !"".equals(v)) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        sb.append("key=" + ConfigConstants.WEIXIN_APP_SECRET);
        //将API返回的数据根据用签名算法进行计算新的签名，用来跟API返回的签名进行比较
        //算出签名
        String resultSign;
        String tobeSign = sb.toString();

        try {
            resultSign = MD5.encode(tobeSign).toUpperCase();
        } catch (Exception e) {
            resultSign = MD5.encode(tobeSign).toUpperCase();
        }
        String WxSign = packageParams.get("sign").toUpperCase();
        return WxSign.equals(resultSign);
    }

}  